# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import logging
from .corelibs import (chkparsdaemon)
from .importapps import (FEATURES)
from .servers import (SetupControllers,SetupDaemons)

logger = logging.getLogger()



def paramfeature(feature,param):
    if feature == 'RAW2NETQ':
        if param in SetupDaemons:
            return SetupDaemons[param].evtnetq
    return param



def chkfeature(params):
    # params = [name:ctrl,feature(dargs)]
    if len(params) != 2:
        logger.error('Two parameters needed for feature')
        return None
    p0 = chkparsdaemon(params[0],SetupDaemons)
    if not p0:
        return None
    dev,name,ctrl = p0
    p1 = params[1].split('(')
    if len(p1) == 0:
        logger.error('Syntax error for feature name')
        return None
    feature= p1[0]
    if feature not in FEATURES:
        logger.error('Unknown feature (syntax error) %s',feature)
        return None
    if len(p1) == 1: 
        dargs = None
    else:
        dargs = p1[1].strip(')')
    return dev,name,ctrl,feature,dargs


def addfeature(params):
    """
    Add feature for controller
    params = [name:ctrl,feature(dargs)]
    """
    p = chkfeature(params)
    if not p:
        return False
    dev,name,ctrl,feature,dargs = p
    if feature in dev.featurenames:
        logger.warning('Feature has been already added %s',feature)
    dev.featurenames.append(feature)
    args = []
    if dargs:
        for a in dargs.split(','):
            args.append(paramfeature(feature,a))
    try:
        if len(args) == 0:
            dev.features.append(FEATURES[feature]())
        else:
            dev.features.append(FEATURES[feature](*args))
    except Exception as e:
        logger.error("%s : %s", repr(e.__class__), str(e))
        logger.error("In adding decoded feature %s" ,feature)
        return False
    return True


def rmfeature(params):
    """
    Remove FEATURE from controller feature list
    """
    p = chkfeature(params)
    if not p:
        return False
    dev,name,ctrl,feature,dargs = p
    if feature not in dev.featurenames:
        logger.error('Feature not yet added %s',feature)
        return False
    i = dev.featurenames.index(feature)
    dev.features[i].close()		#Close coroutine generator
    dev.features.pop(i)
    dev.featurenames.remove(feature)
    logger.info("Feature %s removed for controller %s",feature,ctrl)
    return True
